<template>
  <view class="user-select-container">
    <!-- 搜索区域 -->
    <view class="search-section">
      <uni-search-bar :radius="100" v-model="searchKey" @confirm="handleSearch" placeholder="搜索联系人">
        <view slot="right" class="selected-count" v-if="selectedCount > 0">已选{{ selectedCount }}人</view>
      </uni-search-bar>
    </view>

    <!-- 最近联系人 -->
    <view class="recent-section" v-if="recentContacts.length > 0">
      <view class="section-title">最近联系</view>
      <scroll-view scroll-x class="horizontal-scroll">
        <view
          v-for="(user, index) in recentContacts"
          :key="index"
          class=""
          @click="toggleSelect(user, 'user')"
        >
          <image
            :src="user.pic"
            class="avatar recent-avatar"
            :class="{ selected: isSelected(user, 'user') }"
          />
          <text class="name">{{ user.name }}</text>
        </view>
      </scroll-view>
    </view>

    <!-- 全部联系人 -->
    <view class="all-contacts-section">
      <view class="section-title">好友列表</view>
      <scroll-view scroll-y class="vertical-scroll" :scroll-into-view="scrollIntoId">
        <!-- 字母导航 -->
        <view class="index-bar">
          <text
            v-for="(char, i) in indexChars"
            :key="'char-' + i"
            @click="scrollToIndex(char)"
          >
            {{ char }}
          </text>
        </view>

        <!-- 联系人列表 -->
        <view
          v-for="(user, index) in Contacts"
          :key="index"
          @click="toggleSelect(user, 'friend')"
        >
          <view class="">
            <view class="contact">
              <view class="info">
                <image
                  :src="user.userInfo.nicPic"
                  class="avatar"
                  :class="{ selected: isSelected(user, 'friend') }"
                />
                <view class="">
                  <text class="name">{{ user.userInfo.nicName }}</text>
                </view>
              </view>
              <view
                class="checkbox"
                :class="{ checked: isSelected(user) }"
              >
                <uni-icons
                  type="checkbox-filled"
                  size="24"
                  :color="isSelected(user, 'friend')? '#007AFF' : '#ddd'"
                />
              </view>
            </view>
          </view>
        </view>
      </scroll-view>
    </view>

    <!-- 底部操作栏 -->
    <view class="action-bar" v-if="selectedCount > 0">
      <button class="share-btn" @click="handleShare">
        分享给{{ selectedCount }}位好友
        <uni-icons type="forward" size="18" color="#fff" />
      </button>
    </view>
  </view>
</template>

<script>
const INITIAL_CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ#';

export default {
  data() {
    return {
      product: null,
      recentContacts: [],
      searchKey: '',
      scrollIntoId: '',
      selectedUsers: new Map(), // 使用Map提升查找性能
      Contacts: []
    };
  },
  computed: {
    selectedCount() {
      return this.selectedUsers.size;
    },
    indexChars() {
      return INITIAL_CHARS.split('');
    }
  },
  async onLoad(res) {
    this.product = JSON.parse(decodeURIComponent(res.product));
    await this.stroe();
    await this.getfriend();
  },
  methods: {
    // 取最近联系人存储
    async stroe() {
      try {
        const res = await uni.getStorage({ key:'sessions' });
        console.log('555555', JSON.stringify(res));
        this.recentContacts = res[1].data;
      } catch (e) {
        console.log('取联系人失败', e);
        await uni.setStorage({
          key:'sessions',
          data: []
        });
      }
    },
    async getfriend() {
      try {
        const res = await uni.getStorage({ key: 'addbooks' });
        console.log('res: ' + JSON.stringify(res));
        this.Contacts = res[1].data;
      } catch (e) {
        console.error(e);
      }
    },
    handleSearch() {},
    toggleSelect(user, type) {
      if (type === 'friend') {
        if (this.selectedUsers.has(user.userInfo.userId)) {
          this.selectedUsers.delete(user.userInfo.userId);
        } else {
          this.selectedUsers.set(user.userInfo.userId, user);
        }
      } else if (type === 'user') {
        if (this.selectedUsers.has(user.id)) {
          this.selectedUsers.delete(user.id);
        } else {
          this.selectedUsers.set(user.id, user);
        }
      }
      this.$forceUpdate();
    },
    handleShare() {
      const selected = Array.from(this.selectedUsers.values());
      uni.$emit('share-target-selected', selected);
      uni.navigateBack();
    },
    scrollToIndex(char) {
      this.scrollIntoId = char;
    },
    isSelected(user, type) {
      if (type === 'user') {
        return this.selectedUsers.has(user?.id);
      } else if (type === 'friend') {
        return this.selectedUsers.has(user.userInfo.userId);
      }
      return false;
    }
  }
};
</script>

<style lang="scss" scoped>
.user-select-container {
  height: 100vh;
  display: flex;
  flex-direction: column;

 .avatar {
    width: 80rpx;
    height: 80rpx;
    border-radius: 50%;
    border: 2rpx solid #eee;

    &.selected {
      border-color: #007aff;
      box-shadow: 0 4rpx 12rpx rgba(0, 122, 255, 0.3);
    }
  }

 .index-bar {
    position: fixed;
    right: 20rpx;
    top: 50%;
    transform: translateY(-50%);
    display: flex;
    flex-direction: column;
    font-size: 24rpx;
    color: #666;
  }

 .action-bar {
    position: fixed;
    bottom: 0;
    width: 100%;
    padding: 20rpx;
    background: linear-gradient(to top, #fff 80%, rgba(255, 255, 255, 0.8));

   .share-btn {
      background: #007aff;
      color: white;
      border-radius: 48rpx;
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }
}

.contact {
  display: flex;
  background-color: #eee;
  margin: 10rpx;
  width: 700rpx;
  align-items: center;
  padding-right: 50rpx;
  justify-content: space-between;
}

.info {
  display: flex;
  margin-left: 25rpx;
  padding-right: 50rpx;
  align-items: center;
  padding-right: 20rpx;
}

.horizontal-scroll {
  /* 设置水平滚动样式 */
  white-space: nowrap;
  overflow-x: auto;
  -webkit-overflow-scrolling: touch; /* 优化 iOS 滚动体验 */
}

.section-title {
  /* 标题样式 */
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 10px;
}

.horizontal-scroll > view {
  /* 将内部元素设置为行内块元素 */
  display: inline-block;
  margin-right: 10px; /* 可以根据需要调整元素之间的间距 */
  text-align: center;
}
</style>